import { Injectable } from '@nestjs/common';
import { Merchant } from 'src/entities/Merchant';
import { MerchantDailyIncome } from 'src/entities/MerchantDailyIncome';
import { Platform } from 'src/entities/Platform';
import { PlatformDailyIncome } from 'src/entities/PlatformDailyIncome';
import { Connection } from 'typeorm';

@Injectable()
export class ProfitSettlementService {

    constructor(
        private connection:Connection
    ){}

    async settlement({
        time,
        merchantId,
        subMerchantId,
        profitRate,
        amount,
        consumeEnergy,
        totalTime
    }) {

        let isSuccess = false

        //计算当天整点
        const date = new Date(time * 1000)
        date.setHours(0)
        date.setMinutes(0)
        date.setSeconds(0)

        const dailyTime = date.getTime() / 1000 //当天00:00:00

        const queryRunner = this.connection.createQueryRunner();
        await queryRunner.connect();
        await queryRunner.startTransaction()
        
        

        try {
            
            const platform = await queryRunner.manager.findOne<Platform>(Platform, {
                where : {id : 1},
                lock : {
                    mode : 'pessimistic_read'
                }
            })

            await queryRunner.manager.update<Platform>(Platform, null, {totalAmount : Number(platform.totalAmount) + amount, totalTime : platform.totalTime + totalTime, totalEnergy : platform.totalEnergy + consumeEnergy})

            const platformDaily = await queryRunner.manager.findOne<PlatformDailyIncome>(PlatformDailyIncome, {
                where : {date : dailyTime},
                select : ['id', 'amount', 'time', 'energy']
            })

            if(platformDaily) {
                await queryRunner.manager.update<PlatformDailyIncome>(PlatformDailyIncome, {id : platformDaily.id}, {
                    time : platformDaily.time + totalTime,
                    energy : platformDaily.energy + consumeEnergy,
                    amount : Number(platformDaily.amount) + amount
                })
            }else {
                await queryRunner.manager.insert<PlatformDailyIncome>(PlatformDailyIncome, {
                    time : totalTime,
                    energy : consumeEnergy,
                    amount : amount
                })
            }

            if(merchantId > 0) {
                let merchantProfit:any = 0
                let subMerchantProfit:any = 0
                subMerchantProfit = amount * profitRate / 100
                merchantProfit = amount - subMerchantProfit

                if(merchantProfit > 0 || totalTime > 0 || consumeEnergy > 0) {
                    const merchant = await queryRunner.manager.findOne<Merchant>(Merchant, {
                        where : {merchantId},
                        select : ['amount', 'totalChargeAmount', 'totalChargeEnergy', 'totalChargeTime'],
                        lock : {
                            mode : 'pessimistic_read'
                        }
                    })
    
                    if(merchant) {
                        await queryRunner.manager.update<Merchant>(Merchant, {merchantId}, {
                            amount : Number(merchant.amount) + merchantProfit,
                            totalChargeAmount : Number(merchant.totalChargeAmount) + merchantProfit,
                            totalChargeEnergy : merchant.totalChargeEnergy + consumeEnergy,
                            totalChargeTime : merchant.totalChargeTime + totalTime
                        })

                        const merchantDaily = await queryRunner.manager.findOne<MerchantDailyIncome>(MerchantDailyIncome, {
                            where : {merchantId, date : dailyTime},
                            select : ['id', 'amount', 'time', 'energy']
                        })

                        if(merchantDaily) {
                            await queryRunner.manager.update<MerchantDailyIncome>(MerchantDailyIncome, {id : merchantDaily.id}, {
                                time : merchantDaily.time + totalTime,
                                energy : merchantDaily.energy + consumeEnergy,
                                amount : Number(merchantDaily.amount) + merchantProfit
                            })
                        }else {
                            await queryRunner.manager.insert<MerchantDailyIncome>(MerchantDailyIncome, {
                                merchantId,
                                time : totalTime,
                                energy : consumeEnergy,
                                amount : merchantProfit
                            })
                        }
                    }

                    if(subMerchantId > 0) { //有二级商户
                        const merchant = await queryRunner.manager.findOne<Merchant>(Merchant, {
                            where : {merchantId : subMerchantId},
                            select : ['amount', 'totalChargeAmount', 'totalChargeEnergy', 'totalChargeTime'],
                            lock : {
                                mode : 'pessimistic_read'
                            }
                        })
        
                        if(merchant) {
                            await queryRunner.manager.update<Merchant>(Merchant, {merchantId : subMerchantId}, {
                                amount : Number(merchant.amount) + subMerchantProfit,
                                totalChargeAmount : Number(merchant.totalChargeAmount) + subMerchantProfit,
                                totalChargeEnergy : merchant.totalChargeEnergy + consumeEnergy,
                                totalChargeTime : merchant.totalChargeTime + totalTime
                            })
    
                            const merchantDaily = await queryRunner.manager.findOne<MerchantDailyIncome>(MerchantDailyIncome, {
                                where : {merchantId : subMerchantId, date : dailyTime},
                                select : ['id', 'amount', 'time', 'energy']
                            })
    
                            if(merchantDaily) {
                                await queryRunner.manager.update<MerchantDailyIncome>(MerchantDailyIncome, {id : merchantDaily.id}, {
                                    time : merchantDaily.time + totalTime,
                                    energy : merchantDaily.energy + consumeEnergy,
                                    amount : Number(merchantDaily.amount) + subMerchantProfit
                                })
                            }else {
                                await queryRunner.manager.insert<MerchantDailyIncome>(MerchantDailyIncome, {
                                    merchantId : subMerchantId,
                                    time : totalTime,
                                    energy : consumeEnergy,
                                    amount : subMerchantProfit
                                })
                            }
                        }
                    }
                }

                

            }

            await queryRunner.commitTransaction()

            isSuccess = true


        } catch (error) {
            
        } finally {
            if(isSuccess == false) {
                await queryRunner.rollbackTransaction()
            }

            await queryRunner.release()
        }



    }
}
